/**
 * 作者:hanbo
 * 日期:2019/1/3011:26
 * 描述:
 */

/**
 * 下载文件
 * @param url {String}文件下载网址
 * @param path {String}文件保存路径
 * @param name {String}文件保存名称
 */
    //文件下载
const fs = require("fs");
const Axios = require("axios");
const path = require("path");
const request = require("request");
const mkdirp = require("mkdirp");
const userAgents = require('./userAgents');

function downFile(url, savePath, saveName,addModel, callBack) {
    const filePath = path.join(savePath, saveName);
    if (!fs.existsSync(savePath)) {//判断文件夹是否存在
        mkdirp(savePath, function (err) {
            if (err) {
                console.error(err);
                callBack(2);
            } else {
                downAndSave(url, filePath).then(()=>{
                  callBack(0)
                }).catch(err=>{
                  console.log("下载错误",err);
                  callBack(1)
                })
            }
        });

    } else if (!fs.existsSync(filePath)) {//判断文件是否存在
        downAndSave(url, filePath).then(()=>{
          callBack(0)
        }).catch(err=>{
          console.log("下载错误",err);
          callBack(1)
        })
    }else {
        if(addModel){
            callBack(0)
        }else {
          fs.unlink(filePath,function(err) {
            if(err){
              console.error(err);
              callBack(2);
            }else {
              downAndSave(url, filePath).then(()=>{
                callBack(0)
              }).catch(err=>{
                  console.log("下载错误",err);
                  callBack(1)
              })
            }
          });
        }
    }
}
 function downAndSave(url, filePath) {
  let userAgent = userAgents[parseInt(Math.random() * userAgents.length)];
  // let stream = fs.createWriteStream(filePath);
  return new Promise((resolve, reject) => {
    request({ url: url, encoding: null , headers: {'User-Agent': userAgent}}, (err, response, body) => {
        if(err){
            console.log(err);
          reject()
        }else {
          fs.writeFileSync(filePath, body, { encoding: 'binary' });
          resolve();
        }
    })
  })

  // let downProgress = request({url: url, headers: {'User-Agent': userAgent}}).pipe(stream);
  // downProgress.on("close", function (err) {
  //   if (err) {
  //     console.log("down fail");
  //     callBack(1);
  //   } else {
  //     callBack(0);
  //   }
  // });
  // downProgress.on('error', function (err) {
  //   console.log("错误信息:" + err);
  //   callBack(1);
  // })
}

function getCurrentUrl(url, x, y, z) {
    //需要在以后改进正则，匹配大小写
    let result =url.replace("{x}", x);
    result = result.replace("{y}", y);
    result = result.replace("{z}", z);
    return result;
}

function clearAll(path,callBack){
    
    function delDir(path) {
        let files = [];
        if(fs.existsSync(path)){
            files = fs.readdirSync(path);
            files.forEach((file, index) => {
                console.log("delete"+path);
                let curPath = path + "/" + file;
                if(fs.statSync(curPath).isDirectory()){
                    delDir(curPath); //递归删除文件夹
                } else {
                    fs.unlinkSync(curPath); //删除文件
                }
            });
            fs.rmdirSync(path);

        }else {
            console.log(2);
        }
    }
    delDir(path);
    mkdirp(path, function (err) {
        if (err) {
          console.log(err)
        }
    });
    callBack();
}

exports.downFile = downFile;
exports.getCurrentUrl = getCurrentUrl;
exports.clearAll = clearAll;